package com.qhg.saas_server.aspect;


import com.qhg.saas_server.annotation.Mylog;
import com.qhg.saas_server.pojo.Log;
import com.qhg.saas_server.service.LogService;
import com.qhg.saas_server.utils.IpUtill;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Slf4j
@Component
@Aspect
public class SysLogAspect {

    @Autowired
    LogService logService;

    @Autowired
    HttpServletRequest request;

    @Pointcut("@annotation(com.qhg.saas_server.annotation.Mylog ))")
    public void logPoinCut() {
    }


    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {

        //设置日志存储对象
        Log log = new Log();

        //通过反射获取自定义注解内的value值
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Mylog annotation = method.getAnnotation(Mylog.class);
        String value = annotation.value();
        //获取操作用户的id
        Integer comploId = (Integer)request.getSession().getAttribute("comploId");
        //获取用户ip
        String ipAddr = IpUtill.getIpAddr(request);

        //填充log实体
        log.setLog_comploId(comploId);
        log.setLogIp(ipAddr);
        log.setLogRecord(value);

        //插入操作
        logService.insertLog(log);

    }


}
